import React from 'react'
import { Card, Row, Col, Typography, Button, Image} from 'antd'
import { Link } from 'react-router-dom'
import PropTypes from 'prop-types'
// dateformat 插件 将时间正常显示为 yyyy/mm/dd
import dateformat from 'dateformat'
import { API } from '../../config'
// 引入购物车的方法
import { addProduct } from '../../helper/cart'
import { useDispatch } from 'react-redux'
import { push } from 'connected-react-router'
const { Title, Paragraph } = Typography



export default function ProductItem({
	product,
	showView = true,
	showCart = true,
	imgStyle
}) {
	const dispatch = useDispatch()

	ProductItem.propTypes = {
		product: PropTypes.object.isRequired
	}

	const { name, _id, description, price, sold, category:{ name: category }, createdAt} = product
 
	const addCart = () => {
		addProduct(product, ()  => {
			dispatch(push('/cart'))
		})
	} 

	const showButton = () =>{
		const button = []
		if(showView)
			button.push(
				<Button type="link">
					<Link to={`product/${_id}`} >查看详情</Link>
				</Button>,
			)
		if(showCart)
			button.push(
				<Button type="link" onClick={addCart}>
					加入购物
				</Button>
			)
		return button
	}

	

	return (
		<>
			<Card
				hoverable
				cover={<Image alt="example" style={imgStyle} src={`${API}/product/photo/${_id}`} />}
				actions={showButton()}
			>
				<Title level={5} ellipsis={{ rows: 2}}>{name}</Title>
				<Paragraph ellipsis={{ rows: 2}}>{description}</Paragraph>
				<Row>
					<Col span={12}>价格:{price}</Col>
					<Col span={12}>销量:{sold}</Col>
				</Row>
				<Row>
					<Col span={12}>所属分类:{category}</Col>
					<Col span={12}>上架时间:{dateformat(createdAt, 'yyyy-mm-dd')}</Col>
				</Row>
			</Card>
		</>
	)


}





